let mysql = require('mysql')
let config = require('../config')

let pool = mysql.createPool(config.database)
let trans = (tran) => {
    return new Promise((resolve, reject) => {
        pool.getConnection((err, conn) => {
            if(err) {
                reject(err)
            }else {
                conn.beginTransaction((err) => {
                    if(err) {
                        conn.release()
                        reject(err)
                    }else {
                        let promise = tran(conn)
                        promise.then(result => {
                            conn.commit(err => {
                                if(err) {
                                    reject(err)
                                }else {
                                    resolve(result)
                                }
                            })
                        }).catch(err => {
                            conn.rollback(() => {
                                conn.release()
                                reject(err)
                            })
                        })
                    }
                })
            }
        })
    })
}
trans.query = (conn, sql, params) => {
    return new Promise((resolve, reject) => {
        conn.query(sql, params,(err, result) => {
            if(err) {
                reject(err)
            }else {
                resolve(result)
            }
        })
    })
}
module.exports = trans